package com.haiya.common.exception;

import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.http.HttpStatus;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author qiaoguoqiang
 */
public class ApiError {
    /**
     * 操作调用状态:
     * 4xx客户端错误
     * - 400 BAD_REQUEST
     *
     * 5xx服务器错误
     */
    private HttpStatus status;

    /**
     * 发生错误的日期时间
     */
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd hh:mm:ss")
    private LocalDateTime timestamp;

    /**
     * 用户友好的错误信息
     */
    private String message;

    /**
     * 详细错误信息
     */
    private String debugMessage;

    /**
     * 保存发生的子错误数组。用于表示在单个调用中出现的多个错误。
     * 例如, 校验的时候有多个字段验证失败，用ApiSubError类进行分装。
     */
    private List<ApiSubError> subErrors;

    public ApiError() {
        timestamp = LocalDateTime.now();
    }

    public ApiError(HttpStatus status) {
        this();
        this.status = status;
    }

    public ApiError(HttpStatus status, Throwable ex) {
        this();
        this.status = status;
        this.message = "Unexpected error";
        this.debugMessage = ex.getLocalizedMessage();
    }
    public ApiError(HttpStatus status, String message, Throwable ex) {
        this();
        this.status = status;
        this.message = message;
        this.debugMessage = ex.getLocalizedMessage();
    }
}
